package com.tensquare.base.controller;

import com.tensquare.base.pojo.Label;
import com.tensquare.base.service.LabelService;
import com.tensquare.entity.PageResult;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zzb
 * @create 2020/12/14
 */
@RestController
@RequestMapping("label")
@CrossOrigin
public class LabelController {
    @Autowired
    private LabelService labelService;
    //添加label
    @PostMapping
    public Result add(@RequestBody Label label){
        try {
            labelService.add(label);
            return new Result(true, StatusCode.OK,"添加标签成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"添加标签失败");
        }
    }

    //查询所有标签
    @GetMapping
    public Result findAll(){
        //查询所有标签
        List<Label> labelList = labelService.findAll();
        //返回
        return new Result(true,StatusCode.OK,"查询所有标签成功",labelList);
    }

    //根据id查询标签
    @GetMapping("{labelId}")
    public Result findById(@PathVariable String labelId) {
        try {
            Label label = labelService.findById(labelId);
            return new Result(true, StatusCode.OK, "查询单个标签成功", label);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"查询单个标签失败");

        }

    }

    //修改标签
    @PutMapping("{labelId}")
    public Result update(@PathVariable String labelId,@RequestBody Label label){
        try {
            //将标签id与对象绑定
            label.setId(labelId);
            //进行标签的修改
            labelService.update(label);
            //返回
            return new Result(true,StatusCode.OK,"修改标签成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,StatusCode.OK,"修改标签失败");
        }
    }

    //删除标签
    @DeleteMapping("{labelId}")
    public Result delete(@PathVariable String labelId){
        try {
            labelService.delete(labelId);
            return new Result(true,StatusCode.OK,"删除标签成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,StatusCode.OK,"删除标签失败");
        }
    }

    //标签条件查询
    @PostMapping("search")
    public Result search(@RequestBody Label label){
        //根据条件查询标签集合
        List<Label> labels = labelService.search(label);
        //返回
        return new Result(true,StatusCode.OK,"查询标签成功",labels);
    }

    //进行标签分页查询
    @PostMapping("search/{page}/{size}")
    public Result search(@RequestBody Label label,@PathVariable Integer page,@PathVariable Integer size){
       //根据田间查询标签集合
        PageResult<Label> labels = labelService.search(label, page, size);
        //返回
        return new Result(true,StatusCode.OK,"查询标签成功",labels);
    }
}
